﻿using System;
using System.Linq;
using K9Nano.Configuration.Startup;
using K9Nano.Dependency;
using K9Nano.MultiTenancy;
using K9Nano.Share.Extensions;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace K9Nano.AspNetCore.MultiTenancy.Resolvers
{
    public class HttpHeaderTenantResolveContributor : ITenantResolver, ITransientDependency
    {
        private readonly ILogger _logger;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IMultiTenancyConfig _multiTenancyConfig;

        public HttpHeaderTenantResolveContributor(
            IHttpContextAccessor httpContextAccessor,
            IMultiTenancyConfig multiTenancyConfig,
            ILogger<HttpHeaderTenantResolveContributor> logger)
        {
            _httpContextAccessor = httpContextAccessor;
            _multiTenancyConfig = multiTenancyConfig;
            _logger = logger;
        }

        public Guid? ResolveTenantId()
        {
            var httpContext = _httpContextAccessor.HttpContext;
            if (httpContext == null)
            {
                return null;
            }

            var tenantIdHeader = httpContext.Request.Headers[_multiTenancyConfig.TenantIdResolveKey];
            if (tenantIdHeader == string.Empty || tenantIdHeader.Count < 1)
            {
                return null;
            }

            if (tenantIdHeader.Count > 1)
            {
                _logger.LogWarning(
                    $"HTTP request includes more than one {_multiTenancyConfig.TenantIdResolveKey} header value. First one will be used. All of them: {tenantIdHeader.JoinAsString(", ")}"
                );
            }

            return Guid.TryParse(tenantIdHeader.First(), out var tenantId) ? tenantId : (Guid?)null;
        }
    }
}